package org.demo.szml.perssionservice.config;

import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.demo.szml.api.exception.ApiInvokeBaseException;
import org.demo.szml.api.response.Response;
import org.demo.szml.api.response.ResponseCode;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Objects;

/**
 * @description: 权限服务全局异常处理器
 * @date: 2025/6/19 17:42
 * @version: 1.0
 */
@Slf4j
public class PermissionGlobalExceptionHandler {

    /** 处理其他可鞥的异常信息
     * @param e 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(Exception.class)
    public Response<Void> handleException(Exception e) {
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        return Response.<Void>builder().code(ResponseCode.UNKNOWN_FAILED).build();
    }

    /** 处理调用过程中可能的报错信息
     * @param e 错误信息
     * @return 响应结果
     */
    @ExceptionHandler(ApiInvokeBaseException.class)
    public Response<Void> handleInvokeException(ApiInvokeBaseException e){
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        if (Objects.isNull(e.getShowErrorPrompt())){
            return Response.<Void>builder().code(ResponseCode.UNKNOWN_FAILED).build();
        }
        return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info(e.getShowErrorPrompt()).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if(ObjectUtils.isEmpty(allErrors)){
            return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info("参数错误").build();
        }
        StringBuilder errorInfo = new StringBuilder();
        errorInfo.append("信息不符合要求:");
        for (ObjectError allError : allErrors) {
            errorInfo.append(allError.getDefaultMessage()).append(",");
        }
        errorInfo.append("。");
        return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info(errorInfo.toString()).build();
    }
}
